package cn.wujiangbo.controller.app;

import cn.wujiangbo.constants.Constants;
import cn.wujiangbo.controller.base.BaseController;
import cn.wujiangbo.domain.app.AppUser;
import cn.wujiangbo.dto.token.UserToken;
import cn.wujiangbo.exception.MyException;
import cn.wujiangbo.result.JSONResult;
import cn.wujiangbo.service.app.AppUserService;
import cn.wujiangbo.utils.DateUtils;
import cn.wujiangbo.utils.MyTools;
import cn.wujiangbo.utils.RedisCache;
import cn.wujiangbo.utils.uuid.IdUtils;
import cn.wujiangbo.utils.uuid.UUID;
import cn.wujiangbo.vo.system.LoginSuccessVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>APP 登录相关请求处理</p>
 *
 * @author 波波老师(weixin:javabobo0513)
 */
@RestController
@RequestMapping("/app/login")
public class AppLoginController extends BaseController {

    @Resource
    public AppUserService appUserService;

    @Resource
    public RedisCache redisCache;

    @Value("${easyjava.userDefaultAvatarPath}")
    public String userDefaultAvatarPath;

    /**
     * APP注册接口
     */
    @PostMapping(value = "/register")
    public JSONResult register(@RequestBody AppUser appUser) {
        if (!MyTools.hasLength(appUser.getLoginName())) {
            throw new MyException("账号不能为空！");
        }
        if (!MyTools.hasLength(appUser.getLoginPass())) {
            throw new MyException("密码不能为空！");
        }
        if (appUser.getLoginPass().trim().length() <= 6) {
            throw new MyException("密码长度需要大于6位！");
        }
        //查询手机号是否被注册
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("login_name", appUser.getLoginName());
        AppUser one = appUserService.getOne(queryWrapper);
        if (one != null) {
            throw new MyException("账号已被注册，请更换！");
        }
        //字段赋值
        appUser.setLoginName(appUser.getLoginName().trim());//手机号作为登录账号
        appUser.setLoginPass(appUser.getLoginPass().trim());//登录密码默认为123456
        appUser.setUserImg(userDefaultAvatarPath);//头像
        appUser.setNickName(MyTools.getNickName());//随机昵称
        appUser.setUserStatus(1);//用户状态（1：正常；2：限制登录）
        appUser.setCreateTime(DateUtils.getCurrentLocalDateTime());//创建时间
        appUser.setRegisterTime(DateUtils.getCurrentLocalDateTime());//账号注册时间
        appUser.setUserMoney(new BigDecimal(200));
        //数据入库
        appUserService.save(appUser);
        return JSONResult.successMessage(true, "账号注册成功！");
    }

    /**
     * APP登录接口-账号登录
     */
    @PostMapping(value = "/login")
    public JSONResult login(@RequestBody AppUser appUser) {
        if (!MyTools.hasLength(appUser.getLoginName())) {
            throw new MyException("登录账号不能为空！");
        }
        if (!MyTools.hasLength(appUser.getLoginPass())) {
            throw new MyException("登录密码不能为空！");
        }
        //根据账号查询数据库用户信息
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("login_name", appUser.getLoginName());
        AppUser one = appUserService.getOne(queryWrapper);
        if (one == null) {
            throw new MyException("登录账号不存在！");
        }
        //对比密码
        if (!one.getLoginPass().equals(appUser.getLoginPass())) {
            throw new MyException("登录密码错误！");
        }
        //封装返回值
        LoginSuccessVo vo = new LoginSuccessVo();
        handleUserInfo(one, vo);
        return JSONResult.success(vo);
    }

    //处理用户信息
    public void handleUserInfo(AppUser one, LoginSuccessVo vo){
        //检查用户状态,用户状态（1：正常；2：限制登录）
        if (one.getUserStatus() == 2) {
            throw new MyException("抱歉，您已被限制登录" + (MyTools.hasLength(one.getUserError()) ? "，原因：" + one.getUserError() : "！"));
        }
        //登录成功，记录用户最后登录时间等信息
        one.setLastLoginTime(DateUtils.getCurrentLocalDateTime());
        appUserService.updateById(one);
        //登录密码正确，现在给前端颁发token
        //用户信息存Redis的key值
        String redisToken = IdUtils.fastSimpleUUID();
        UserToken userToken = new UserToken();
        userToken.setUserId(one.getId());
        userToken.setNickName(one.getNickName());
        redisCache.setCacheObject(Constants.LOGIN_TOKEN_KEY_APP + redisToken,
                JSONObject.toJSONString(userToken), Constants.TOKEN_REDIS_ALIVE_TIME, TimeUnit.HOURS);
        //封装返回值
        vo.setToken(redisToken);
        vo.setAppUser(one);
    }

    /**
     * APP登录接口-短信验证码登录
     */
    @PostMapping(value = "/smsLogin")
    public JSONResult smsLogin(@RequestBody AppUser appUser) {
        if (!MyTools.hasLength(appUser.getLoginName())) {
            throw new MyException("登录账号不能为空！");
        }
        //根据账号查询数据库用户信息
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("login_name", appUser.getLoginName());
        AppUser one = appUserService.getOne(queryWrapper);
        if (one == null) {
            throw new MyException("登录账号不存在！");
        }
        //封装返回值
        LoginSuccessVo vo = new LoginSuccessVo();
        handleUserInfo(one, vo);
        return JSONResult.success(vo);
    }
}
